<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>扁平数据转tree</title>
</head>
<body>
  
  <script>
    const arr = [
      {id: 1, name: '部门1', pid: 0},
      {id: 2, name: '部门2', pid: 1},
      {id: 3, name: '部门3', pid: 1},
      {id: 4, name: '部门4', pid: 3},
      {id: 5, name: '部门5', pid: 4}
    ]

    // 使用递归
    function arrayToTree(data, result, pid) {
      data.forEach(item => {
        if(pid === item.pid) {
          const newItem = {...item, children: []}
          result.push(newItem)
          arrayToTree(data, newItem.children, newItem.id)
        }
      })
      return result;
    }

    const treeData = arrayToTree(arr, [], 0)
    console.log('treeData', treeData)
  </script>
</body>
</html>